'use strict';
const { HttpException } = require('@utils/http-exception');

module.exports = () => {
  return async (ctx, next) => {
    try {
      await next();
    } catch (err) {
      // 生产环境让异常出现在控制台
      const isHttpException = err instanceof HttpException; // 检测自定义错误提示
      const isDev = ctx.app.config.env === 'local';
      if (!isHttpException && isDev) {
        console.error(err);
      }
      const reqData = {
        msg: '服务器出现了错误 /(ㄒoㄒ)/~~',
        errorCode: 9999,
        request: `${ctx.method} ${ctx.path}`,
      };
      let statusCode = 504;
      if (isHttpException) {
        reqData.msg = err.message || err.msg;
        reqData.errorCode = err.errorCode;
        statusCode = err.code;
      }

      ctx.body = reqData;
      ctx.status = statusCode;
    }
  };
};
